package com.dimeng;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dimeng.utils.CommonUtil;
import com.dimeng.utils.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * @author write by ccn<br>
 * <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-5-16 上午10:24:13<br>
 * descrition:产品类别浏览搜索视图
 */
public class CatBrowseActivity extends SuperActivity {
	private static final long serialVersionUID = -6082573393447773170L;
	private TextView prodCatSearchTitleTextView;
	/**获取子类别列表的url**/
	private final String CHILD_CAT_URL = Constant.HOST_URL+"categoryBrowse.do";
	private int catId;//类别ID
	private String catName;//类别名称
	private int catLevel = 0;
	private ImageButton searchButton;
	/**类目级别及其对应的ListView数据**/
	private Map<Integer,List<HashMap<String,String>>> catLevelDataListMap = new HashMap<Integer,List<HashMap<String,String>>>();
	private Map<Integer,String> catLevelCatNameMap = new HashMap<Integer,String>();
	/**产品类目浏览时的当前类目列表**/
	private List<HashMap<String,String>> prodCatList = new ArrayList<HashMap<String,String>>();
	private ListView listView;
	private SimpleAdapter adapter;
	private Gson gson = new Gson();
	private LinearLayout loadingLayout;
	private RelativeLayout firstLineCatLayout;
	private TextView firstCatNameTextView;
	private TextView firstCatIdTextView;
	
	private Thread loadThread;
	private int msgWhat = 0;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			msgWhat = msg.what;
			switch(msgWhat){
				case 1:
					if(catLevel == 2){
						setFirstLayoutVisibility(View.VISIBLE);
					}
					catName = catLevelCatNameMap.get(catLevel);
					firstCatIdTextView.setText(catId+"");
					firstCatIdTextView.setVisibility(View.GONE);
					firstCatNameTextView.setText("所有"+catName);
					adapter.notifyDataSetChanged();
					String str = catName == null?"":" > "+catName;
					prodCatSearchTitleTextView.setText(getResources().getString(R.string.prodCatSearch)+str);
					break;
				case 2:
					adapter.notifyDataSetChanged();
					Toast.makeText(CatBrowseActivity.this, Constant.NET_ERROR, Toast.LENGTH_LONG).show();
					break;
				default:
					break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cat_browse);
		prodCatSearchTitleTextView = (TextView) findViewById(R.id.prodCatSearchTitle);
		catName = catLevelCatNameMap.get(catLevel);
		String str = catName == null?"":" > "+catName;
		prodCatSearchTitleTextView.setText(getResources().getString(R.string.prodCatSearch)+str);
		
		listView = (ListView) findViewById(R.id.catBrowseListViewId);
		
		searchButton = (ImageButton) findViewById(R.id.searchButton);
		CommonUtil.setButtonFocusChanged(searchButton);
		
		firstLineCatLayout = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.firstline_cat_item, null);
		listView.addHeaderView(firstLineCatLayout);
		firstCatIdTextView = (TextView) firstLineCatLayout.findViewById(R.id.firstCatId);
		firstCatNameTextView = (TextView) firstLineCatLayout.findViewById(R.id.firstCatName);
		setFirstLayoutVisibility(View.GONE);
		
		loadingLayout = CommonUtil.loadingLayout(CatBrowseActivity.this);
		listView.addFooterView(loadingLayout);
		adapter = new SimpleAdapter(this,prodCatList,R.layout.cat_browse_item,new String[]{"catName","isLeaf"},new int[]{R.id.catName,R.id.isLeaf});
		listView.setAdapter(adapter);
		
		Intent intent = getIntent();
		catId = intent.getIntExtra("catId", 0);//获取请求的类别id参数
		startLoadDataThread(CHILD_CAT_URL+"?catId="+catId);
		
		searchButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent intent = new Intent(CatBrowseActivity.this,SupplyBuySearchActivity.class);
				intent.putExtra("searchType", 1);
				CatBrowseActivity.this.startActivity(intent);
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapter, View view, int location,
					long id) {
				String isLeaf = "";
				if(0 == location){
					catId = Integer.parseInt(firstCatIdTextView.getText().toString());
					isLeaf = "0";
				} else {
					@SuppressWarnings("unchecked")
					HashMap<String,String> selectedMap = (HashMap<String, String>) listView.getItemAtPosition(location);
					catId = Integer.parseInt(selectedMap.get("catId"));
					catName = selectedMap.get("catName");
					isLeaf = selectedMap.get("isLeaf");
				}
				if("0".equals(isLeaf)){//如果为产品类别叶子结点 则执行搜索动作
					Intent intent = new Intent(CatBrowseActivity.this,SupplyBuySearchActivity.class);
					intent.putExtra("catId", catId);
					intent.putExtra("searchType", 0);
					intent.putExtra("catName", catName);
					CatBrowseActivity.this.startActivity(intent);
				} else {//加载子类别
					String url = CHILD_CAT_URL + "?catId="+catId;
					startLoadDataThread(url);
				}
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			if(--catLevel > 0) {
				catName = catLevelCatNameMap.get(catLevel);
				String str = catName == null?"":" > "+catName;
				prodCatSearchTitleTextView.setText(getResources().getString(R.string.prodCatSearch)+str);
				List<HashMap<String,String>> paretCatDataList = catLevelDataListMap.get(catLevel);
				prodCatList.clear();
				prodCatList.addAll(paretCatDataList);
				if(catLevel == 1){
					setFirstLayoutVisibility(View.GONE);
				}
				adapter.notifyDataSetChanged();
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void setFirstLayoutVisibility(int visible){
		firstLineCatLayout.setVisibility(visible);
		for(int i=0;i<firstLineCatLayout.getChildCount();i++){
			View childView = firstLineCatLayout.getChildAt(i);
			childView.setVisibility(visible);
		}
	}
	
	/**启动线程下载数据**/
	private void startLoadDataThread(String url){
		if(null == loadThread || !loadThread.isAlive()){
			loadThread = new LoadProdCatThread(url);
			loadThread.start();
			loadingLayout.setVisibility(View.GONE);
		}
	}
	
	class LoadProdCatThread extends Thread{
		private String url;
		public LoadProdCatThread(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			int i = 0;
			Message msg = new Message();
			while(true) {
				try {
					if(++i == 2){//网络故障
						msg.what = 2;
						break;
					}
					String json = CommonUtil.getContent(url, Constant.CHARSET_GBK,false);//load product category list from remote server
					List<HashMap<String, String>> data = gson.fromJson(json, new TypeToken<List<HashMap<String, String>>>(){}.getType());
					if(null != data && data.size() != 0){
						catLevel++;
						if(null != catName)
							catLevelCatNameMap.put(catLevel, catName);
						
						catLevelDataListMap.put(catLevel, data);
						prodCatList.clear();
						prodCatList.addAll(data);
						msg.what = 1;
					} else {//无数据
						msg.what = 0;
					}
					break;
				} catch (Exception e) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					e.printStackTrace();
				}
			}
			handler.sendMessage(msg);
		}
	}
}
